﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using DevExpress.XtraEditors;

#endregion

namespace DevTools.ClassStuffGenerator.Components
{
    public static class Generator
    {
        public static string Generate(List<Item> items, string template, string[] filters)
        {
            StringBuilder builder = new StringBuilder();

            string RegularExpression = string.Format(@"<#.*?#>");

            Regex regex = new Regex(RegularExpression, RegexOptions.Singleline);
            MatchCollection matches = regex.Matches(template);
            string[] splitedTexts = regex.Split(template);

            for (int i = 0; i < splitedTexts.Length; i++)
            {
                builder.Append(splitedTexts[i]);

                if (i < matches.Count)
                {
                    string macro = matches[i].Value.Substring(2, matches[i].Value.Length - 4);

                    foreach (var item in items)
                    {
                        if (filters.Length != 0 && item.FieldName.BelongsTo(filters) == false)
                            continue;

                        GenerateCore(builder, macro, item);
                    }
                }
            }

            return builder.ToString();
        }

        private static void GenerateCore(StringBuilder builder, string text, Item item)
        {
            Regex regex = new Regex("{[CF][NFSIM][NPC]}", RegexOptions.Singleline);
            MatchCollection matches = regex.Matches(text);
            string[] splitedTexts = regex.Split(text);

            for (int i = 0; i < splitedTexts.Length; i++)
            {
                builder.Append(splitedTexts[i]);

                if (i < matches.Count)
                {
                    string macro = matches[i].Value.Substring(1, matches[i].Value.Length - 2);
                    builder.Append(item.GeneateCode(macro));
                }
            }
        }
    }
}